import { useEffect, useState, useRef } from 'react';
import { Card, Button, Select, Form, Col, Row, message } from 'antd';
import { useTranslation } from 'react-i18next';
import {
  BulbOutlined, AlignCenterOutlined, ExclamationCircleOutlined
} from '@ant-design/icons';

import {
  lineledon, lineledoff, ledopen, ledoff, resetled, workinglight, workingoff,
  positionlist
} from "@/api/test";
import { configState } from '@/api/common';
import { COLOR_OPTIONS, THREE_COLOR_OPTIONS } from "@/utils/constants"
import { listToOptions } from "@/utils";
import './index.scss';

// 提取常量
const CHANNEL_OPTIONS = [
  { label: 'channel1', value: 'channel1' },
  { label: 'channel2', value: 'channel2' }
];

function Test() {
  const { t } = useTranslation();
  const [form] = Form.useForm();
  const [form2] = Form.useForm();
  const [form3] = Form.useForm();
  const [status, setStatus] = useState(false);
  const [options3, setOptions3] = useState([]);
  const [msg, setMsg] = useState(t("message.noTestAction"));

  // 提取重复的卡片标题渲染
  const renderCardTitle = (icon, titleKey) => (
    <div className='title'>
      {icon}
      <span className="tit">{t(titleKey)}</span>
    </div>
  );

  // 提取公共的 Select 配置
  const selectProps = {
    getPopupContainer: triggerNode => triggerNode.parentElement
  };

  function onFinish(values) {
    lineledon(values).then(res => {
      message.success(`${t('message.test.light') + values.channel_num},${t('message.test.color') + values.channel_color},${t('message.test.start')}`);
    });
  }

  function onFinish2(values) {
    ledopen(values).then(res => {
      message.success(`${t('message.test.lightAddr') + values.light_led},${t('message.test.star')}`);
    });
  }

  function onFinish3(values) {
    workinglight(values).then(res => {
      setMsg(`${t('message.test.channel') + values.workchannel + ',' + t('message.test.statusLight') + values.workcolor + ',' + 'on off True'}`);
    });
  }

  function close() {
    let values = form.getFieldsValue();
    lineledoff(form.getFieldsValue()).then(res => {
      message.success(`${t('message.test.light') + values.channel_num},${t('message.test.color') + values.channel_color},${t('message.test.over')}`);
    });
  }

  function close2() {
    let param = {
      light_led_color: form2.getFieldValue("light_led_color"),
      off_led: form2.getFieldValue("light_led")
    }
    ledoff(param).then(res => {
      message.success(`${t('message.test.lightAddr') + param.off_led},${t('message.test.over')}`);
    });
  }

  function close3() {
    let values = form3.getFieldsValue();
    workingoff(form3.getFieldsValue()).then(res => {
      setMsg(`${t('message.test.channel') + values.workchannel + ',' + t('message.test.statusLight') + values.workcolor + ',' + 'on off False'}`);
    });
  }

  function reset() {
    resetled().then(res => {
      message.success(`${t('message.test.reset')}`);
    });
  }
  function getLoad() {
    configState().then(res => {
      setStatus(res);
    })
    positionlist().then(res => {
      setOptions3(listToOptions(res));
    })
  }
  useEffect(() => {
    getLoad();
  }, [])

  return (
    <div className="test-container">
      <div className="row-a1">
        <div className="left">
          {/* 灯带测试 */}
          <div className="con-a1">
            <Card title={renderCardTitle(<BulbOutlined style={{ color: '#08c' }} />, 'test.stripTest')}>
              <Form
                form={form}
                initialValues={{ channel_num: 'channel1', channel_color: 'red' }}
                labelCol={{ span: 6 }}
                onFinish={onFinish}
              >
                <Row>
                  <Col span={12}>
                    <Form.Item label={t("test.channel")} name="channel_num">
                      <Select options={CHANNEL_OPTIONS} {...selectProps} />
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item label={t("test.color")} name="channel_color">
                      <Select options={COLOR_OPTIONS} {...selectProps} />
                    </Form.Item>
                  </Col>
                  <Col span={24}>
                    <Form.Item>
                      <Button className='submit-btn' type="primary" htmlType="submit">
                        {t("test.stripAllOn")}
                      </Button>
                      <Button className='close-btn' onClick={close} type="primary">
                        {t("test.stripAllOff")}
                      </Button>
                    </Form.Item>
                  </Col>
                </Row>
              </Form>
            </Card>
          </div>

          {/* 位置操作测试 */}
          <div className="con-a1">
            <Card title={renderCardTitle(<AlignCenterOutlined style={{ color: '#08c' }} />, 'test.locationOperationTest')}>
              <Form
                form={form2}
                initialValues={{ light_led: "", light_led_color: 'red' }}
                labelCol={{ span: 6 }}
                onFinish={onFinish2}
              >
                <Row>
                  <Col span={12}>
                    <Form.Item label={t("test.location")} name="light_led">
                      <Select options={options3} {...selectProps} />
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item label={t("test.color")} name="light_led_color">
                      <Select options={COLOR_OPTIONS} {...selectProps} />
                    </Form.Item>
                  </Col>
                  <Col span={24}>
                    <Form.Item>
                      <Button className='submit-btn' type="primary" htmlType="submit">
                        {t("test.turnOn")}
                      </Button>
                      <Button className='close-btn' onClick={close2} type="primary">
                        {t("test.turnOff")}
                      </Button>
                      <Button className='reset-btn' onClick={reset} type="primary">
                        {t("test.reset")}
                      </Button>
                    </Form.Item>
                  </Col>
                </Row>
              </Form>
            </Card>
          </div>

          {/* 状态灯测试 */}
          <div className="con-a1">
            <Card title={renderCardTitle(<BulbOutlined style={{ color: '#08c' }} />, 'test.statusLightTest')}>
              <Form
                form={form3}
                initialValues={{ workchannel: 'channel1', workcolor: 'red' }}
                labelCol={{ span: 6 }}
                onFinish={onFinish3}
              >
                <Row>
                  <Col span={12}>
                    <Form.Item label={t("test.channel")} name="workchannel">
                      <Select options={CHANNEL_OPTIONS} {...selectProps} />
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item label={t("test.color")} name="workcolor">
                      <Select options={THREE_COLOR_OPTIONS} {...selectProps} />
                    </Form.Item>
                  </Col>
                  <Col span={24}>
                    <Form.Item>
                      <Button className='submit-btn' type="primary" htmlType="submit">
                        {t("test.turnOn")}
                      </Button>
                      <Button className='close-btn' onClick={close3} type="primary">
                        {t("test.turnOff")}
                      </Button>
                    </Form.Item>
                  </Col>
                </Row>
              </Form>
            </Card>
          </div>
        </div>

        <div className="right">
          {/* 测试状态 */}
          <div className="con-a3">
            <Card title={renderCardTitle(<ExclamationCircleOutlined style={{ color: '#08c' }} />, 'test.testStatus')}>
              <div className="list">
                <div className="li">
                  {t("test.testMessage")}：{msg}
                </div>
                <div className="li">
                  {t("common.configStatus")}：{(status ? t("common.loadSuccess") : t("common.loadErrorTips"))}
                </div>
              </div>
            </Card>
          </div>
        </div>
      </div>
    </div>
  )
}

export default Test;